import os

def append_txt_content(fi1, folder_path):
    """
    从文件夹中的子文件提取标题和正文（多行支持），追加到fi1。
    """
    with open(fi1, 'a', encoding='utf-8') as outfile:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                if file.endswith('.txt'):
                    txt_path = os.path.join(root, file)
                    try:
                        with open(txt_path, 'r', encoding='utf-8') as f:
                            lines = [line.strip() for line in f.readlines()]
                            lines = [l for l in lines if l != '']  # 去掉空行

                            if len(lines) < 3:
                                print(f"⚠️ 跳过格式不完整文件：{txt_path}")
                                continue

                            title = lines[0]
                            # 正文从第3行开始，到出现“评论”或文件结尾为止
                            body_lines = []
                            for line in lines[2:]:
                                if line.startswith("评论"):
                                    break
                                body_lines.append(line)
                                #添加额外字符
                                body_lines.append("\n")
                            body = "\n".join(body_lines)

                            outfile.write(f"## {title}\n{body}\n\n")
                            print(f"✅ 已追加：{title}")
                    except Exception as e:
                        print(f"❌ 读取文件出错：{txt_path}\n错误信息：{e}")

if __name__ == "__main__":
    fi1 = input("请输入主txt文件路径：").strip('"') or r"C:\pro\IT\Python\Py1\日语\temp\videos\Books\riyuall.txt"
    folder_path = input("请输入文件夹路径：").strip('"') or r"C:\pro\IT\Python\Py1\日语\temp\videos\Books\日语文章"
    append_txt_content(fi1, folder_path)
    print("\n🎉 全部完成！")
